﻿using System;
using NUnit.Framework;
using Coogle.Core;
using Coogle.DataAccess;
using System.Data.SqlClient;

namespace Coogle.Tests.DataAccess
{
    [TestFixture]
    public class SelectContainerTests
    {
        private static readonly String s_connectionString = "Data Source=(local);initial catalog=SpedizTest;Integrated Security=SSPI";
        private ContainerCode toFind;
        private DbGateway db;
        private SelectContainer selectContainer;

        [SetUp]
        public void SetUp()
        {
            Execute(s_connectionString, "DELETE FROM [dbo].[Containers]");
            toFind = new ContainerCode("MEDU", 748572, 9);
            db = new DbGateway(s_connectionString);
            selectContainer = new SelectContainer(toFind);
        }

        [Test]
        public void FindContainerInEmptyArchive()
        {
            var found = db.FindSingle(selectContainer);

            Assert.That(found, Is.Null);
        }

        [Test]
        public void FindContainerNotInArchive()
        {
            Execute(s_connectionString, "INSERT INTO [dbo].[Containers]([Sign], [Number], [Checkdigit], [Type])VALUES('XXXX', 123456, 7,'test') ");
            Execute(s_connectionString, "INSERT INTO [dbo].[Containers]([Sign], [Number], [Checkdigit], [Type])VALUES('ZZZZ', 987654, 3,'test') ");

            var found = db.FindSingle(selectContainer);

            Assert.That(found, Is.Null);
        }

        [Test]
        public void FindContainerInArchive()
        {
            Execute(s_connectionString, "INSERT INTO [dbo].[Containers]([Sign], [Number], [Checkdigit], [Type])VALUES('XXXX', 123456, 7,'test') ");
            Execute(s_connectionString, "INSERT INTO [dbo].[Containers]([Sign], [Number], [Checkdigit], [Type])VALUES('" + toFind.Sign + "', " + toFind.Number + ", " + toFind.Check + ",'test') ");
            var expected = new Container(toFind, new ContainerType("test"));

            var found = db.FindSingle(selectContainer);

            Assert.That(found, Is.EqualTo(expected));
        }

        private void Execute(string connectionString, string commandText)
        {
            using (var cn = new SqlConnection(connectionString))
            using (var cmd = new SqlCommand(commandText, cn))
            {
                cn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}
